#include <QtGui/QApplication>
#include <unistd.h>
#include "mainwindow.h"
#include "ipclogicmanager.h"
#include "ipcnetworkmanager.h"
#define MAX_CMD_LEN 256

int gIWho = PRO_N;
void setupUiAndLogicConnection(MainWindow *, LogicManager *);
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    IPCLogicManager *logicManager;
    MainWindow *uiWindow;
    IPCNetworkManager *networkManager;
    int appReuslt;
    
    if(strstr(argv[0] ,"qt_messenger") != 0)
    {
        gIWho = PRO_L;
        //NetworkManager *networkManager = new NetworkManager();
        printf("ui booting...\n");
        logicManager = new IPCLogicManager();
        uiWindow = new MainWindow();
        
        // Setup Connection
        setupUiAndLogicConnection(uiWindow, logicManager->mLogic);
        //setupNetworkAndLogicConnection(networkManager, logicManager);

        uiWindow->show();
        uiWindow->login();
        appReuslt = app.exec();
        delete uiWindow;
        delete logicManager; 
    }
    else
    {
        gIWho = PRO_N;
        printf("%s:network booting...\n",argv[0]);
        networkManager = new IPCNetworkManager();
        appReuslt = app.exec();
        delete networkManager;
    }
    
    return appReuslt;
}

void setupUiAndLogicConnection(MainWindow * uiWindow, LogicManager * logicManager)
{
    // Ui to Logic
    QObject::connect(uiWindow, SIGNAL(closeWindow()),
                     logicManager, SLOT(onSendLogout()));
    QObject::connect(uiWindow, SIGNAL(sendMessage(const QString&, const QString&)),
                     logicManager, SLOT(onSendMessage(const QString &, const QString &)));
    QObject::connect(uiWindow, SIGNAL(stopChating(const QString&)),
                     logicManager, SLOT(onCloseConnection(const QString&)));
    QObject::connect(uiWindow, SIGNAL(login(const QString&)),
                     logicManager, SLOT(onSendLogin(const QString &)));

    // Logic to Ui
    QObject::connect(logicManager, SIGNAL(networkStatusChanged(eNetworkStatus)),
                     uiWindow, SLOT(onNetworkStatusChanged(eNetworkStatus)));
    QObject::connect(logicManager, SIGNAL(loginStatusReceived(eLoginStatus)),
                     uiWindow, SLOT(onLoginResultReceived(eLoginStatus)));
    QObject::connect(logicManager, SIGNAL(userListChanged(const QList<userInfo> &)),
                     uiWindow, SLOT(onContactListUpdated(const QList<userInfo>&)));
    QObject::connect(logicManager, SIGNAL(messageUpdate(const QString &, const QList<recordInfo> &)),
                     uiWindow, SLOT(onMessageUpdated(const QString&, const QList<recordInfo>&)));
}

